import axios from 'axios';
import { urlIp } from '../composables/value';
import { useUsersStore } from '../store/user';
import { ElMessage } from 'element-plus';

// 格式化时间
export const formatDate = (time: any) => {
  const date = new Date(time);
  return formatDateString(date);
};

const formatDateString = (date:any) => {
  const year = date.getFullYear();
  const month = pad2(date.getMonth() + 1);
  const day = pad2(date.getDate());
  const hours = pad2(date.getHours());
  const minutes = pad2(date.getMinutes());
  const seconds = pad2(date.getSeconds());
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const pad2 = (number:number) => {
  return (number < 10 ? '0' : '') + number;
};
  
export const postWithToken = async (url : string, param?: any) => {
  const userStore = useUsersStore();
  const response = await axios.post(urlIp.value + url, param, {headers: {token: userStore.token}});
  if (response.data.code == 202) {
    // 用户未登录
    ElMessage.error(response.data.msg);
    userStore.clearStorage();
  }
  return response.data;
}

export const post = async (url : string, param?: any) => {
  const response = await axios.post(urlIp.value + url, param);
  return response.data;
}

// 下载文件，携带token，跨域问题在后端解决的
export const getDownloadFile = async (url : string) => {
  const userStore = useUsersStore();
  const response = await axios.get(urlIp.value + url, {headers: {token: userStore.token}, responseType: "blob"});
  // 处理返回的文件流
  const blob = new Blob([response.data], {type: response.headers['content-type']}); // 创建Blob对象，要写content-type，从后端拿到的content-type，为了设置文件类型，这里是xlsx
  const link = document.createElement("a");
  // link.style.display = 'none';
  // document.body.appendChild(link);
  link.href = URL.createObjectURL(blob);
  // 文件名，后端通过content-disposition传的，截取=后面的文件名称，decodeURI解码中文
  link.download = decodeURI(response.headers['content-disposition'].match(/=(.*)$/)[1]);
  link.click();
  // 释放URL对象
  URL.revokeObjectURL(link.href);
}